package com.ecloud.hbase.util;

import com.ecloud.common.ResultEnum;
import com.ecloud.common.exception.ServerException;
import com.ecloud.hbase.config.HbaseConnFactory;
import com.ecloud.hbase.standard.GetInner;
import com.ecloud.hbase.standard.PutInner;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自己实现的Template
 *
 * @author Squbi
 */
@Component
public class HbaseTemplate {
    @Autowired
    HbaseConnFactory factory;

    public void put(String tableName, String rowKey, PutInner inner) {
        Put put = inner.putIn(new Put(Bytes.toBytes(rowKey)));
        put(tableName, put);
    }

    public Result get(String tableName, String rowKey, GetInner inner) {
        Get get = inner.getIn(new Get(Bytes.toBytes(rowKey)));
        return get(tableName, get);
    }

    public void put(String tableName, Put put) {
        Table table;
        try {
            table = factory.getTable(tableName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServerException(ResultEnum.DB_INNER_ERROR, e.getMessage());
        }
        try {
            table.put(put);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServerException(ResultEnum.DB_INNER_ERROR, e.getMessage());
        } finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Result get(String tableName, Get get) {
        Table table;
        try {
            table = factory.getTable(tableName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServerException(ResultEnum.DB_INNER_ERROR, e.getMessage());
        }
        try {
            return table.get(get);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServerException(ResultEnum.DB_INNER_ERROR, e.getMessage());
        } finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
